package com.my.study.common.security.gitee;

import com.my.study.dto.JwtUserDto;
import com.my.study.entity.MyUserEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.client.userinfo.CustomUserTypesOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

/**
 * @author yidujun
 * @date 2022/8/9 19:38
 */
//@Component("giteeOAuth2UserService")
public class GiteeOAuth2UserService extends CustomUserTypesOAuth2UserService {

    
    public GiteeOAuth2UserService(Map<String, Class<? extends OAuth2User>> customUserTypes) {
        super(customUserTypes);
    }

    @Override
    public JwtUserDto loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        OAuth2User oAuth2User = super.loadUser(userRequest);

        Map<String, Object> attributes = oAuth2User.getAttributes();
        String user_name = (String) attributes.get("user_name");

        MyUserEntity myUserEntity = new MyUserEntity();
        myUserEntity.setUserName(user_name);
        JwtUserDto userDto = new JwtUserDto(myUserEntity);
        userDto.setAttributes(oAuth2User.getAttributes());
        Collection<? extends GrantedAuthority> authorities = oAuth2User.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            if (userDto.getAuthorities() == null) {
                userDto.setAuthorities(new ArrayList<>());
            }
            userDto.getAuthorities().add(authority);
        }

        return userDto;
    }
}
